import '@nomicfoundation/hardhat-ethers'
import 'hardhat-deploy'
import { task } from 'hardhat/config'
import { HardhatRuntimeEnvironment } from 'hardhat/types'
import { networkConfig } from '../helper-hardhat-config'
import { NFTPoolBurnAndMint, WrappedMyToken } from '../typechain-types'

export const burnAndCross = task('burn-and-cross')
  .addOptionalParam('chainselector', 'chain selector of the destination chain')
  .addOptionalParam('receiver', 'receiver address on the destination chain')
  .addParam('tokenid', 'token id to lock and cross') // 命令行不支持大写，如果写成tokenId,命令行得写成token-id,比较麻烦
  .setAction(async (taskArgs, hre: HardhatRuntimeEnvironment) => {
    let chainSelector = ''
    let receiver = ''
    const tokenId = taskArgs.tokenid
    const { firstAccount } = await hre.getNamedAccounts()

    if (taskArgs.chainselector) {
      chainSelector = taskArgs.chainselector
    } else {
      chainSelector = networkConfig[hre.network.config.chainId! as keyof typeof networkConfig].companionChainSelector
      console.log('chainSelector is not set in command')
    }
    console.log(`chainSelector is ${chainSelector}`)

    if (taskArgs.receiver) {
      receiver = taskArgs.receiver
    } else {
      // 基于当前网络找到在hardhat.config.ts中配置companionNetworks，
      const nFTPoolLockAndReleaseDeployment =
        await hre.companionNetworks.destChain.deployments.get('NFTPoolLockAndRelease')
      receiver = nFTPoolLockAndReleaseDeployment.address
      console.log('receiver is not set in command')
    }
    console.log(`receiver is ${receiver}`)

    // transfer link token to address of the pool
    const linkTokenAddress = networkConfig[hre.network.config.chainId! as keyof typeof networkConfig].linkToken
    const linkToken = await hre.ethers.getContractAt('LinkToken', linkTokenAddress)
    const nftPoolBurnAndMint = await hre.ethers.getContract<NFTPoolBurnAndMint>('NFTPoolBurnAndMint', firstAccount)
    const transferTx = await linkToken.transfer(nftPoolBurnAndMint.target, hre.ethers.parseEther('10'))
    await transferTx.wait(6)
    const balance = await linkToken.balanceOf(nftPoolBurnAndMint.target)
    console.log(`balance of the pool is ${balance}`)

    // appprove pool address to call transferFrom
    const wnft = await hre.ethers.getContract<WrappedMyToken>('WrappedMyToken', firstAccount)
    await wnft.approve(nftPoolBurnAndMint.target, tokenId)
    console.log('appprove success')

    // call burnAndSendNFT
    const burnAndSendNFT = await nftPoolBurnAndMint.burnAndSendNFT(tokenId, firstAccount, chainSelector, receiver)
    console.log(`ccip transaction is sent, the tx hash is ${burnAndSendNFT.hash}`)
  })
